import os
import openai
import requests
import random
from typing import List, Optional
from models import Character, ChatMessage

class OpenAIClient:
    def generate_response(self, character: Character, message: str, 
                         skill: Optional[str] = None, 
                         history: List[ChatMessage] = [],
                         api_key: str = None) -> str:
        """生成英文回复"""
        
        if not api_key:
            raise ValueError("OpenAI API key not provided")
        
        openai.api_key = api_key
        
        system_prompt = self._build_system_prompt(character, skill)
        
        messages = [{"role": "system", "content": system_prompt}]
        
        for msg in history:
            messages.append({"role": msg.role, "content": msg.content})
        
        messages.append({"role": "user", "content": message})
        
        try:
            response = openai.ChatCompletion.create(
                model="gpt-4",
                messages=messages,
                temperature=0.7,
                max_tokens=500
            )
            
            return response.choices[0].message.content
            
        except openai.error.AuthenticationError:
            raise Exception("Invalid OpenAI API key")
        except openai.error.RateLimitError:
            raise Exception("API quota exceeded")
        except Exception as e:
            raise Exception(f"OpenAI API error: {str(e)}")
    
    def _build_system_prompt(self, character: Character, skill: Optional[str] = None) -> str:
        prompt = character.system_prompt
        
        if skill == 'tech' and character.name == "Iron Man":
            prompt += "\nFocus on discussing technology, engineering, and innovation."
        elif skill == 'humor' and character.name == "Iron Man":
            prompt += "\nEmphasize your sarcastic and witty personality. Make jokes and clever remarks."
        elif skill == 'espionage' and character.name == "Black Widow":
            prompt += "\nShare insights about spycraft, intelligence gathering, and covert operations."
        elif skill == 'combat' and character.name == "Black Widow":
            prompt += "\nDiscuss fighting techniques, strategy, and your combat experiences."
        
        prompt += "\nAlways stay in character and respond in English."
        return prompt

class FreeAIClient:
    def generate_response(self, character: Character, message: str, 
                         skill: Optional[str] = None, 
                         history: List[ChatMessage] = []) -> str:
        """（FREE）生成英文回复"""
        
        try:
            # 尝试使用Hugging Face API
            hf_token = os.getenv('HF_TOKEN')
            if hf_token:
                return self._call_huggingface(character, message, hf_token)
            else:
                # 使用改进的英文模拟回复
                return self._get_enhanced_english_response(character, message, skill)
                
        except Exception as e:
            # 免费服务失败时回退到模拟回复
            return self._get_enhanced_english_response(character, message, skill)
    
    def _call_huggingface(self, character, message, token):
        """调用Hugging Face API生成英文回复"""
        # 实现具体的Hugging Face API调用
        # 暂时返回英文模拟回复
        return f"{character.name}: This is an experimental response. Please configure Hugging Face API for actual use."
    
    def _get_enhanced_english_response(self, character, message, skill):
        """获取增强的英文模拟回复"""
        responses = self._get_character_english_responses(character.name)
        
        # 关键词匹配
        message_lower = message.lower()
        for keyword, response in self._get_english_keyword_responses().items():
            if keyword in message_lower:
                return response
        
        return random.choice(responses)
    
    def _get_character_english_responses(self, character_name):
        """获取角色回复库"""
        responses = {
            "Iron Man": [
                "You know, I'm not saying I'm responsible for this world, but I am responsible for making it better.",
                "My armor? It's not just a suit, it's a technological marvel. JARVIS, say hello.",
                "Sometimes you gotta run before you can walk. That's how innovation works.",
                "Genius, billionaire, playboy, philanthropist. But you can just call me Tony."
            ],
            "Black Widow": [
                "I've got red in my ledger. I'd like to wipe it out.",
                "Espionage isn't about brute force. It's about intelligence and precision.",
                "In our line of work, trust is a luxury we can't always afford.",
                "I'm always picking up after you boys. Someone has to be the responsible one."
            ]
        }
        return responses.get(character_name, ["I'm ready for our conversation. What would you like to talk about?"])
    
    def _get_english_keyword_responses(self):
        """英文关键词回复"""
        return {
            "hello": "Hey there! What's on your mind today?",
            "hi": "Hi! Ready to chat?",
            "who are you": "I think you already know who I am. Let's keep talking.",
            "thank": "You're welcome. I'm always happy to help.",
            "bye": "See you around. Don't do anything I wouldn't do!"
        }

class MockAIClient:
    def generate_response(self, character: Character, message: str, 
                         skill: Optional[str] = None, 
                         history: List[ChatMessage] = []) -> str:
        """生成英文回复"""
        free_client = FreeAIClient()
        return free_client._get_enhanced_english_response(character, message, skill)